<template>
  <view class="page">
    <view class="header" v-if="items.length > 0">
      <text class="header-title">播放历史 ({{ items.length }})</text>
      <button class="clear-all-btn" @click="clearAllHistory">清空全部</button>
    </view>
    <scroll-view class="list" scroll-y>
      <view class="item" v-for="(h, i) in items" :key="h.id">
        <image class="cover" :src="h.cover" mode="aspectFill" @click="goToPlayer(h)" />
        <view class="meta" @click="goToPlayer(h)">
          <text class="title">{{ h.title }}</text>
          <text class="artist">{{ h.artist }}</text>
          <text class="time">{{ formatTime(h.play_time) }}</text>
        </view>
        <view class="actions">
          <button class="play-btn" @click.stop="togglePlayMusic(h)">
            <image class="play-icon" :src="isPlaying && currentPlayingId === h.id ? '/static/stop.png' : '/static/start.png'" mode="aspectFit"></image>
          </button>
          <button class="delete-btn" @click.stop="deleteHistory(h)">
            <image class="delete-icon" src="/static/delete.png" mode="aspectFit"></image>
          </button>
        </view>
      </view>
      <view class="empty" v-if="!items.length">暂无历史</view>
    </scroll-view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const API_BASE_URL = 'http://localhost:3001'
const userId = ref('0')
const items = ref<any[]>([])
const isPlaying = ref(false)
const currentPlayingId = ref<number | null>(null)

const fetchList = async () => {
  try {
    const res = await uni.request({ url: `${API_BASE_URL}/api/users/${userId.value}/history`, method: 'GET' })
    const data = res?.data as any
    items.value = Array.isArray(data?.items) ? data.items : []
  } catch {
    items.value = []
  }
}

const formatTime = (timeStr: string) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    return '今天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else if (days === 1) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}

const playMusic = (item: any) => {
  console.log('播放音乐:', item.title)
  uni.showToast({ title: `播放: ${item.title}`, icon: 'none' })
  // 这里可以添加实际的播放逻辑
}

const goToPlayer = (item: any) => {
  // 跳转到播放页面
  const songData = {
    id: item.music_id,
    title: item.title,
    artist: item.artist,
    cover: item.cover,
    duration: 180
  }
  uni.navigateTo({
    url: `/pages/player/index?song=${encodeURIComponent(JSON.stringify(songData))}`
  })
}

const togglePlayMusic = (item: any) => {
  if (currentPlayingId.value === item.id && isPlaying.value) {
    // 如果当前正在播放这首歌曲，则暂停
    isPlaying.value = false
    currentPlayingId.value = null
    console.log('暂停音乐:', item.title)
    uni.showToast({ title: `暂停: ${item.title}`, icon: 'none' })
  } else {
    // 播放新歌曲或继续播放
    isPlaying.value = true
    currentPlayingId.value = item.id
    console.log('播放音乐:', item.title)
    uni.showToast({ title: `播放: ${item.title}`, icon: 'none' })
  }
  
  // 跳转到播放页面
  const songData = {
    id: item.music_id,
    title: item.title,
    artist: item.artist,
    cover: item.cover,
    duration: 180
  }
  uni.navigateTo({
    url: `/pages/player/index?song=${encodeURIComponent(JSON.stringify(songData))}`
  })
}

const deleteHistory = async (item: any) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除"${item.title}"的播放记录吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await uni.request({
            url: `${API_BASE_URL}/api/users/${userId.value}/history/${item.id}`,
            method: 'DELETE'
          })
          // 从列表中移除该项
          items.value = items.value.filter(h => h.id !== item.id)
          uni.showToast({ title: '删除成功', icon: 'success' })
        } catch (err) {
          console.log('删除播放历史失败:', err)
          uni.showToast({ title: '删除失败', icon: 'none' })
        }
      }
    }
  })
}

const clearAllHistory = () => {
  uni.showModal({
    title: '确认清空',
    content: '确定要清空所有播放历史吗？此操作不可恢复。',
    success: async (res) => {
      if (res.confirm) {
        try {
          // 使用批量删除API
          const result = await uni.request({
            url: `${API_BASE_URL}/api/users/${userId.value}/history`,
            method: 'DELETE'
          })
          // 清空列表
          items.value = []
          uni.showToast({ title: '清空成功', icon: 'success' })
        } catch (err) {
          console.log('清空播放历史失败:', err)
          uni.showToast({ title: '清空失败', icon: 'none' })
        }
      }
    }
  })
}

onLoad((query) => {
  const localUser = uni.getStorageSync('user')
  if (!localUser?.id) {
    return uni.redirectTo({ url: '/pages/auth/login' })
  }
  userId.value = String(query?.userId || localUser.id)
  fetchList()
})
</script>

<style>
.page { min-height: 100vh; background: #f7f8fa; }
.header { display: flex; align-items: center; padding: 20rpx 30rpx; background: #fff; border-bottom: 1rpx solid #eee; }
.header-title { font-size: 32rpx; color: #333; font-weight: 600; flex: 1; }
.clear-all-btn { background: #ff4d4f; color: #fff; border: none; border-radius: 6rpx; padding: 8rpx 16rpx; font-size: 20rpx; }
.list { height: calc(100vh - 100rpx); }
.item { display: flex; align-items: center; padding: 20rpx 24rpx; background: #fff; border-bottom: 1rpx solid #eee; cursor: pointer; }
.item:hover { background: #f8f9fa; }
.cover { width: 100rpx; height: 100rpx; border-radius: 10rpx; margin-right: 16rpx; cursor: pointer; transition: transform 0.2s ease; }
.cover:hover { transform: scale(1.05); }
.meta { flex: 1; display: flex; flex-direction: column; }
.title { font-size: 28rpx; color: #333; }
.artist { font-size: 24rpx; color: #999; margin-top: 6rpx; }
.time { font-size: 22rpx; color: #bbb; margin-top: 6rpx; }
.actions { display: flex; align-items: center; gap: 10rpx; }
.play-btn { background: none; border: none; padding: 10rpx; }
.delete-btn { background: none; border: none; padding: 10rpx; }
.play-icon { width: 32rpx; height: 32rpx; }
.delete-icon { width: 28rpx; height: 28rpx; }
.empty { text-align: center; color: #999; padding: 60rpx 0; }
</style>




